import localForage from 'localforage';

export class Storage {
  private db: LocalForage;
  private projectCode: string;
  private userEmail: string;

  constructor(storeName: string, projectCode: string, userEmail: string) {
    this.projectCode = projectCode;
    this.userEmail = userEmail;
    this.db = localForage.createInstance({
      driver: localForage.INDEXEDDB,
      name: 'fanwei',
      storeName,
      description: 'storage for 1.1.0',
    });
  }

  private getKey(key: string): string {
    return [key, this.projectCode, this.userEmail].join('-');
  }

  getStorage(): LocalForage {
    return this.db;
  }

  async getItem(key: string): Promise<unknown> {
    try {
      return await this.getStorage().getItem(this.getKey(key));
    } catch (error) {
      console.error(`Error getting item ${key}:`, error);
      throw error;
    }
  }

  async setItem(key: string, value: unknown): Promise<void> {
    try {
      await this.getStorage().setItem(this.getKey(key), value);
    } catch (error) {
      console.error(`Error setting item ${key}:`, error);
      throw error;
    }
  }

  async removeItem(key: string): Promise<void> {
    try {
      await this.getStorage().removeItem(this.getKey(key));
    } catch (error) {
      console.error(`Error removing item ${key}:`, error);
      throw error;
    }
  }
}

export const MyIndexedDB = new Storage('DataList', 'project123', 'user@example.com');